#include <QFileInfo>
#include <QSettings>
#include <QDir>
#include "urlutils.h"
#include "episodes.h"


QString ago(QDateTime dt) {
    QDateTime current = QDateTime::currentDateTime();
    int days = dt.daysTo(current);
    if (days > 1)
        return QString ("%1 days ago").arg(dt.daysTo(current));
    int seconds = dt.msecsTo(current) / 1000;
    int minutes = seconds / 60;
    int hours = minutes / 60;
    if (hours > 1) {
        return QString("%1 hours ago").arg(hours);
    }
    if (minutes > 1) {
        return QString("%1 minutes ago").arg(minutes);
    }
    if (seconds < 0) {
        return QString("Just now (timeshifted)");
    }
    return QString("%1 seconds ago").arg(seconds);
}


bool Episode::isAvailable() const {
    QFileInfo finfo(downloadPath());
    return finfo.exists();
}

uint qHash(Episode e) {
    return qHash(e.downloadPath());
}

QString Episode::downloadPath() const {
    QString localFile = UrlUtils::toLocalFile(downloadLink);

//    qDebug() << "localFile: " << localFile;
    QFileInfo finfo (localFile);
    QString fileName = finfo.fileName();
    if (!fileName.endsWith(".mp3", Qt::CaseInsensitive)) {
        if (!subscription->badDates)
            fileName = pubDate.toString("yyyyMMdd-hhmm") + ".mp3";
        else
            fileName = fileName.left(25).simplified() + ".mp3";
    }
//    qDebug() << "filename: " << fileName;
    return subscription->downloadPath(fileName);
}

bool Episode::isComplete() const {
    if (description.isEmpty()) return false;
    if (downloadLink.isEmpty()) return false;
    if (name.isEmpty()) return false;
    if (pubDate == QDateTime()) return false;   
    return true;
}

// ************************************* Subscription  ************************


QDateTime Subscription::lastChecked() const {
    QDateTime retval;
    QString episodesXml = downloadPath("episodes.xml");
    QFileInfo finfo(episodesXml);
    if (finfo.exists()) retval = finfo.lastModified();
    return retval;
}

QString Subscription::downloadPath(QString fileName) const {
    QSettings s;
    QDir podcastDir(s.value("podcastdir").toString());
    if (!podcastDir.exists(name)) {
        podcastDir.mkdir(name);
    }
    podcastDir.cd(name);
    QString retval = podcastDir.filePath(fileName);
    return retval;
}


